package com.dullong.firedocmanager.itext;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

@Service
public class PDFReaderImpl implements PDFReader {

	@Override
	public Map<String, Object> getPdfFileText(String filename) {
		Map<String, Object> m = new HashMap<String, Object>();
		PdfReader pdfReader = null;
		try {
			pdfReader = new PdfReader(filename);
			PdfReaderContentParser parser = new PdfReaderContentParser(
					pdfReader);
			StringBuffer stringBuffer = new StringBuffer();
			TextExtractionStrategy strategy;
			int page = pdfReader.getNumberOfPages();
			for (int i = 1; i <= page; i++) {
				strategy = parser.processContent(i,
						new SimpleTextExtractionStrategy());
				String text = strategy.getResultantText();
				stringBuffer.append(text);
			}
			m.put("page", page);
			m.put("body", stringBuffer.toString());

			return m;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (pdfReader != null)
				pdfReader.close();
		}
		return m;
	}

	public static void main(String[] s) {
		Map<String, Object> ss = new PDFReaderImpl()
				.getPdfFileText("D:\\fileopload\\files\\2014\\01\\21\\1.pdf");
		System.out.println(ss);
	}

}
